﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Syngine.Components.Animations
{
	public class AnimationCollection : ICollection<Animation>, IPlayable
	{
		private readonly PlayableState _state = PlayableState.Playing;
		private List<Animation> _animations = new List<Animation>();

		public Animation this[int index]
		{
			get
			{
				return _animations[index];
			}
			set
			{
				_animations[index] = value;
			}
		}

		public Animation this[string name]
		{
			get
			{
				return _animations.First(a => a.Name == name);
			}
			set
			{
				if (value != null)
				{
					if (!_animations.Contains(value))
					{
						Add(value);
					}

					value.Name = name;
				}
			}
		}

		public int Count
		{
			get
			{
				return _animations.Count;
			}
		}

		public bool IsReadOnly
		{
			get
			{
				return false;
			}
		}

		PlayableState IPlayable.State
		{
			get
			{
				return _state;
			}
		}

		public void Play()
		{
			for (int i = 0; i < _animations.Count; i++)
			{
				_animations[i].Play();
			}
		}

		public void Stop()
		{
			for (int i = 0; i < _animations.Count; i++)
			{
				_animations[i].Stop();
			}
		}

		public void Pause()
		{
			for (int i = 0; i < _animations.Count; i++)
			{
				_animations[i].Pause();
			}
		}

		public void LoadContent(LoadContext context)
		{
			for (int i = 0; i < _animations.Count; i++)
			{
				_animations[i].LoadContent(context);
			}
		}

		public void UnloadContent()
		{
			for (int i = 0; i < _animations.Count; i++)
			{
				_animations[i].UnloadContent();
			}
		}

		public void Update(UpdateContext context)
		{
			for (int i = 0; i < _animations.Count; i++)
			{
				_animations[i].Update(context);
			}
		}

		public void Draw(DrawContext context)
		{
			for (int i = 0; i < _animations.Count; i++)
			{
				_animations[i].Draw(context);
			}
		}

		public void Add(Animation item)
		{
			if (!item.IsInitialized)
			{
				item.Initialize();
			}

			_animations.Add(item);
		}

		public void Clear()
		{
			_animations.Clear();
		}

		public bool Contains(Animation item)
		{
			return _animations.Contains(item);
		}

		public void CopyTo(Animation[] array, int arrayIndex)
		{
			_animations.CopyTo(array, arrayIndex);
		}

		public bool Remove(Animation item)
		{
			return _animations.Remove(item);
		}

		public IEnumerator<Animation> GetEnumerator()
		{
			return _animations.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
}
